from fastapi import FastAPI,Form,staticfiles
import uvicorn
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html

# 创建一个FastAPI实例
# 我们在创建FastAPI实例时，禁用了默认的Swagger UI和Redoc，因为这两个UI默认是远程服务器加载的，非常慢，这里我们自己重新提供Swagger UI和Redoc
app = FastAPI(docs_url=None, redoc_url=None)

# 静态文件挂载
app.mount("/static", staticfiles.StaticFiles(directory="../statics"), name="static")

# 重新提供Swagger UI和Redoc的路由
# 这里写路径的时候指定了include_in_schema=False表示这个路由不会出现在生成的API文档当中
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

@app.get("/redoc", include_in_schema=False)
async def custom_redoc():
    return get_redoc_html(
        openapi_url = "/openapi.json",
        title = "Redoc for FastAPI",
        redoc_js_url="/static/redoc.standalone.js"
    )

# 请求体参数 - 表单参数
@app.post("/api/users/login/")
async def login(
        username: str = Form(
            ...,
            title="用户名",
            description="用户名不能为空",
            min_length=5,
            max_length=10
        ),
        password: str = Form(
            ...,
            title="密码",
            description="密码不能为空",
            min_length=6,
            max_length=20
        )
):
    return {"username": username, "password": password}


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)